package com.zj.jdbc2ThreadLocal.tools;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: BeanHandler
 * @Description: 将结果集转换成bean对象的处理器
 * @author: 孤傲苍狼
 * @date: 2014-10-5 下午12:00:33
 *
 */
public class BeanHandler implements ResultSetHandler {
    private Class<?>  clazz;
    private Map<String,String> colomnToFieldMap=new HashMap<>();
    public BeanHandler(Class<?>  clazz) {
        this.clazz=clazz;
        Field[] fields=clazz.getDeclaredFields();
        for(int i=0;i<fields.length;i++){
            colomnToFieldMap.put(clazz.getName()+"."+fields[i].getName().toLowerCase(),fields[i].getName());
        }
        System.out.println(colomnToFieldMap);
    }

    public Object handler(ResultSet rs) {
        try{
            if(!rs.next()){
                return null;
            }
            Object bean = clazz.newInstance();
            //得到结果集元数据
            ResultSetMetaData metadata = rs.getMetaData();
            int columnCount = metadata.getColumnCount();//得到结果集中有几列数据
            for(int i=0;i<columnCount;i++){
                String coulmnName = metadata.getColumnName(i+1).toLowerCase();//得到每列的列名
                Object coulmnData = rs.getObject(i+1);
                String field=colomnToFieldMap.get(clazz.getClass().getName()+"."+coulmnName.toLowerCase());
                if(field!=null) {
                    Field f = clazz.getClass().getDeclaredField(field);//反射出类上列名对应的属性
                    f.setAccessible(true);
                    f.set(bean, coulmnData);
                }
            }
            return bean;
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
